package cn.mynb.util;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

public class HibernateDaoBase {

	private Session session;

	public HibernateDaoBase() {
		this.session = HibernateUtil.getSession();
	}

	/**
	 * 保存操作
	 * 
	 * @param obj
	 * @return 返回0..1 保存成功或失败
	 * @throws Exception
	 */
	public int saveObject(Object obj) throws Exception {
		int ret = 0;
		try {
			session.beginTransaction();
			session.save(obj);
			session.beginTransaction().commit();
			ret = 1;
		} catch (Exception e) {
			throw e;
		} finally {
			HibernateUtil.closeSession(session);
		}
		return ret;
	}

	/**
	 * 保存操作
	 * 
	 * @param obj
	 * @return 成功的话返回一个Serializable，否者返回0,当前保存数据的ID值
	 * @throws Exception
	 */
	public Serializable saveObjectSerializable(Object obj) throws Exception {
		Serializable ret = 0;
		try {
			session.beginTransaction();
			ret = session.save(obj);
			session.beginTransaction().commit();
		} catch (Exception e) {
			throw e;
		} finally {
			HibernateUtil.closeSession(session);
		}
		return ret;
	}

	/**
	 * 删除单行数据(以对象的方式)
	 * 
	 * @param obj
	 * @return 返回0..1 删除成功或失败
	 * @throws Exception
	 */
	public int deleteSingleObject(Object obj) throws Exception {
		int ret = 0;
		try {
			session.beginTransaction();
			session.delete(obj);
			session.beginTransaction().commit();
			ret = 1;
		} catch (Exception e) {
			throw e;
		} finally {
			HibernateUtil.closeSession(session);
		}
		return ret;
	}

	/**
	 * 批量删除多行行数据(以对象的方式)
	 * 
	 * @param obj
	 * @return 返回0..1 删除成功或失败
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public int deleteBatchObject(List list) throws Exception {
		int ret = 0;
		try {
			session.beginTransaction();

			for (int i = 0; i < list.size(); i++) {
				session.delete(list.get(i));
				if (i % 20 == 0) {
					session.flush();
					session.clear();
				}
			}
			session.beginTransaction().commit();
			ret = 1;
		} catch (Exception e) {
			throw e;
		} finally {
			HibernateUtil.closeSession(session);
		}
		return ret;
	}

	/**
	 * (实体删除)单个删除，按参数删除 delete PO where id=?
	 * 
	 * @param obj
	 *            传入HQL，new String[] {"10"} ,多条件属性删除
	 * @return 返回0..1 删除成功或失败
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public int deleteHQLObject(Object hql, Object param) throws Exception {
		int ret = 0;
		try {
			session.beginTransaction();

			Query query = session.createQuery(hql.toString());
			List list = (List)param ;
			if (param != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					query.setParameter(i, list.get(i));
				}
			}
			ret = query.executeUpdate();
			session.beginTransaction().commit();
			if (ret > 0) {
				ret = 1;
			}
		} catch (Exception e) {
			throw e;
		} finally {
			HibernateUtil.closeSession(session);
		}
		return ret;
	}
	
	@SuppressWarnings("unchecked")
	public int deleteHQLObjectList(Object hql, Object param) throws Exception {
		int ret = 0;
		try {
			session.beginTransaction();

			Query query = session.createQuery(hql.toString());
			
			List list = (List)param ;
			if (param != null && list.size()> 0) {
				for (int i = 0; i < list.size(); i++) {
					query.setParameter(i, list.get(i));
				}
			}
			ret = query.executeUpdate();
			session.beginTransaction().commit();
			if (ret > 0) {
				ret = 1;
			}
		} catch (Exception e) {
			throw e;
		} finally {
			HibernateUtil.closeSession(session);
		}
		return ret;
	}

	/**
	 * 修改操作
	 * 
	 * @param obj
	 *            传入一个对象
	 * @return 返回0..1 修改成功或失败
	 * @throws Exception
	 */
	public int updateObject(Object obj) throws Exception {
		int ret = 0;
		try {
			session.beginTransaction();
			session.update(obj);
			session.beginTransaction().commit();
			ret = 1;
		} catch (Exception e) {
			throw e;
		} finally {
			HibernateUtil.closeSession(session);
		}
		return ret;
	}

	/**
	 * 按属性批量修改操作(单个)
	 * 参数要么是字符串数组，要么是整型数组
	 * @param hql
	 *            传入HQL，new String[] {"11","10","9"}
	 * @return 返回0..1 修改成功或失败
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public int updateHQLBatchObject(Object hql, Object param) throws Exception {
		int ret = 0;
		try {
			session.beginTransaction();
			List list = (List)param ;
			Query query = session.createQuery(hql.toString());
			if (param != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					query.setParameter(i, list.get(i));
				}
			}
			ret = query.executeUpdate();
			session.beginTransaction().commit();
			if (ret > 0) {
				ret = 1;
			}
		} catch (Exception e) {
			throw e;
		} finally {
			HibernateUtil.closeSession(session);
		}
		return ret;
	}

	/**
	 * 按ID查询返回单个
	 * 
	 * @param clazz
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public Object queryByIdObject(Class clazz, int id) throws Exception {
		return session.get(clazz, id);
	}

	/**
	 * 按某个属性查询，返回单个
	 * 
	 * @param hql
	 * @param param
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public Object querySingleObject(Object hql, Object param) throws Exception {
		Object obj = null ;
		try {
			Query query = session.createQuery(hql.toString());
			
			List list = (List)param ;
			if(param != null && list.size() > 0) {
				for(int i=0; i<list.size(); i++) {
					query.setParameter(i, list.get(i));
				}
			}
			obj = query.uniqueResult() ;
		} catch (Exception e) {
			throw e;
		}
		return obj ;
	}

	/**
	 * 按某个属性查询，返回多个
	 * 
	 * @param hql
	 * @param param
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public List queryDoubleObject(Object hql, Object param) throws Exception {
		List list = null;
		try {
			Query query = session.createQuery(hql.toString());
			
			List listParam = (List)param ;
			if(param != null && listParam.size() > 0) {
				for(int i=0; i<listParam.size(); i++) {
					query.setParameter(i, listParam.get(i));
				}
			}
			list = query.list();
		} catch (Exception e) {
			throw e;
		}
		return list;
	}

	/**
	 * 查询所有
	 * 
	 * @param hql
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public List queryAllObject(Object hql) throws Exception {
		List list = new ArrayList();
		try {
			Query query = session.createQuery(hql.toString());
			list = query.list();
		} catch (Exception e) {
			throw e;
		}
		return list;
	}

	/**
	 * 分页查询
	 * 
	 * @param hql
	 * @param param
	 *            传入数组
	 * @param offset
	 * @param pageSize
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public PageModel searchPage(String hql, String countHQL, List param, int offset,
			int pageSize) throws Exception {

		Query query = null;
		PageModel pm = null;
		try {
			int total = this.countDB(countHQL);
			System.out.println("总记录数:"+total);
			
			query = session.createQuery(hql);
			
			if (param != null && param.size() > 0) {
				for (int i = 0; i < param.size(); i++) {
					query.setParameter(i, param.get(i)) ;
				}
			}
			query.setFirstResult(offset) ;
			query.setMaxResults(pageSize) ;
			
			pm = new PageModel();
			pm.setTotal(total);
			pm.setPageSize(pageSize) ;
			pm.setPageData(query.list());
		} catch (Exception e) {
			throw e;
		}
		return pm;
	}
	
	/**
	 * 覆写分页方法，带一个参数
	 * @param hql
	 * @param offset
	 * @param pageSize
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public PageModel searchPage(String hql,String countHQL, Object param,int offset,
			int pageSize) throws Exception {
		
		System.out.println(param);
		
		List list = new ArrayList() ;
		if(null != param) 
			list.add(param) ;
		return searchPage(hql,countHQL,list, offset, pageSize) ;
	}
	
	/**
	 * 覆写分页方法，不带参数分页
	 * @param hql
	 * @param offset
	 * @param pageSize
	 * @return
	 * @throws Exception
	 */
	public PageModel searchPage(String hql,String countHQL, int offset,
			int pageSize) throws Exception {
		return searchPage(hql,countHQL,null, offset, pageSize) ;
	}

	/**
	 * 获得总记录数
	 * 
	 * @param hql
	 * @return
	 * @throws Exception
	 */
	public int countDB(String hql) throws Exception {
		String subhql = this.appendHQL(hql);
		try {
			Query query = session.createQuery(subhql);
			return ((Long) query.uniqueResult()).intValue();
		} catch (Exception e) {
			throw e;
		}
	}

	/**
	 * 根据HQL语句，获得查找总记录数的HQL语句 如： form Student s where s.pid is null 经过转换，可以得到
	 * select count(*) from Student s where s.pid is null
	 * 
	 * @param hql
	 * @return
	 * @throws Exception
	 */
	public String appendHQL(String hql) throws Exception {

		int index = hql.indexOf("from");

		if (index == 0) {
			return "select count(*) " + hql.substring(index);
		} else {
			throw new Exception("不正确的HQL，无法拼装统计查询语句!");
		}
	}

	public static void main(String[] args) {
		
	}

}
